package com.pengxun.manager.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.pengxun.common.constant.RedisPrefix;
import com.pengxun.common.utils.ShiroSaltUtils;
import com.pengxun.manager.dao.system.UserinfoDao;
import com.pengxun.manager.enums.UserTypeEnums;
import com.pengxun.manager.enums.UserinfoStatusEnum;
import com.pengxun.manager.model.system.Company;
import com.pengxun.manager.model.system.Role;
import com.pengxun.manager.model.system.UserRole;
import com.pengxun.manager.model.system.Userinfo;
import com.pengxun.manager.service.system.CompanyService;
import com.pengxun.manager.service.system.LoginService;
import com.pengxun.manager.service.system.RoleService;
import com.pengxun.manager.service.system.UserRoleService;
import com.pengxun.manager.service.system.UserinfoService;
import com.pengxun.manager.vo.ChangePasswordVO;
import com.pengxun.manager.vo.ResetPasswordEmailVO;
import com.pengxun.manager.vo.UserinfoSearchVO;
import com.pengxun.manager.vo.UserinfoVO;
import com.pengxun.manager.vo.UserinfoValidateVO;
import com.szeastroc.common.exception.EastrocException;
import com.szeastroc.common.jdbc.page.Page;
import com.szeastroc.common.utils.ValidationUtils;

@Service
public class UserinfoServiceImpl implements UserinfoService {

    @Resource
    private UserinfoDao userinfoDao;



    @Resource
    private LoginService loginService;

 



    @Resource
    private CompanyService companyService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleService roleService;

    private static final String DEFAULT_PASSWORD = "Aa1234";



    @Override
    public int createUser(Userinfo userinfo) {
        ValidationUtils.validate(userinfo);

        // 1 平台管理员：新增用户  可选公司，选用户类型是公司管理员或者普通用户
        // 2 公司管理员：新增只能是自己公司  管理员或者普通用户
        Userinfo currentUser = loginService.getCurrentUser();

        //判断账户
        if (userinfoDao.findByAccount(userinfo.getAccount()) != null) {
            throw new EastrocException("该用户名已被占用");
        }

        if (StringUtils.isNotBlank(userinfo.getEmail())) {
            if (userinfoDao.findByPhoneOrEmail(userinfo.getEmail()) != null) {
                throw new EastrocException("该邮箱已被占用");
            }
        }

        if (StringUtils.isNotBlank(userinfo.getMobile())) {
            if (userinfoDao.findByPhoneOrEmail(userinfo.getMobile()) != null) {
                throw new EastrocException("该手机号已被占用");
            }
        }

        String salt = RandomStringUtils.randomNumeric(4);
        String password = ShiroSaltUtils.generatePassword(DEFAULT_PASSWORD, salt);
        userinfo.setSalt(salt);
        userinfo.setPassword(password);
        if (userinfo.getStatus() == null) {
            userinfo.setStatus(UserinfoStatusEnum.USABLE.getStatus());
        }
        return userinfoDao.insert(userinfo);
    }
    
    public int insert(Userinfo userinfo) {
        ValidationUtils.validate(userinfo);

        // 1 平台管理员：新增用户  可选公司，选用户类型是公司管理员或者普通用户
        // 2 公司管理员：新增只能是自己公司  管理员或者普通用户
        Userinfo currentUser = loginService.getCurrentUser();

        //判断账户
        if (userinfoDao.findByAccount(userinfo.getAccount()) != null) {
            throw new EastrocException("该用户名已被占用");
        }

        if (StringUtils.isNotBlank(userinfo.getEmail())) {
            if (userinfoDao.findByPhoneOrEmail(userinfo.getEmail()) != null) {
                throw new EastrocException("该邮箱已被占用");
            }
        }

        if (StringUtils.isNotBlank(userinfo.getMobile())) {
            if (userinfoDao.findByPhoneOrEmail(userinfo.getMobile()) != null) {
                throw new EastrocException("该手机号已被占用");
            }
        }

        String salt = RandomStringUtils.randomNumeric(4);
        String password = ShiroSaltUtils.generatePassword(DEFAULT_PASSWORD, salt);
        userinfo.setSalt(salt);
        userinfo.setPassword(password);
        userinfo.setCompanyId(currentUser.getCompanyId());
        if (userinfo.getStatus() == null) {
            userinfo.setStatus(UserinfoStatusEnum.USABLE.getStatus());
        }
        return userinfoDao.insert(userinfo);
    }

    @Override
    public int update(Userinfo userinfo) {
        ValidationUtils.validate(userinfo);

        if (StringUtils.isNotBlank(userinfo.getEmail())) {
        	Userinfo oldUserinfo = userinfoDao.findByPhoneOrEmail(userinfo.getEmail());
            if (oldUserinfo != null&&!userinfo.getUserId().equals(oldUserinfo.getUserId())) {
                throw new EastrocException("该邮箱已被占用");
            }
        }

        if (StringUtils.isNotBlank(userinfo.getMobile())) {
            if (userinfoDao.findByPhoneOrEmail(userinfo.getMobile()) != null) {
                throw new EastrocException("该手机号已被占用");
            }
        }

        Userinfo currentUser = loginService.getCurrentUser();
        userinfo.setUpdateBy(currentUser.getUserId());
        userinfo.setUpdateDate(new Date());
        return userinfoDao.update(userinfo);
    }

    @Override
    public int delete(Long userId) {
        Userinfo user = new Userinfo();
        user.setUserId(userId);
        user.setStatus(UserinfoStatusEnum.DELETE.getStatus());
        return userinfoDao.update(user);
    }

    @Override
    public Page findByPage(UserinfoSearchVO userinfoSearchVO) {

        Userinfo currentUser = loginService.getCurrentUser();
        //公司用户
        if (!currentUser.getUserType().equals(UserTypeEnums.PLATFORM_ADMIN.getType())) {
            userinfoSearchVO.setCompanyId(currentUser.getCompanyId());
        }
        List<Userinfo> userinfos = userinfoDao.findByPage(userinfoSearchVO);

        List<UserinfoVO> userinfoVOS = new ArrayList<>();
        userinfos.forEach(user -> {
            userinfoVOS.add(getUserinfoVO(user));
        });

        userinfoSearchVO.setData(userinfoVOS);
        return (Page) userinfoSearchVO;
    }

    public UserinfoVO findByUserId(Integer userId) {

        Userinfo user = userinfoDao.findByUserId(userId);
        return getUserinfoVO(user);
    }

    /**
     * 生成返回前端的用户信息，包括部门公司，角色等信息
     *
     * @param user
     * @return
     */
    UserinfoVO getUserinfoVO(Userinfo user) {
        UserinfoVO userVO = new UserinfoVO();
        BeanUtils.copyProperties(user, userVO);

        Company company = companyService.findByCompanyId(user.getCompanyId());
        if (company != null) {
            userVO.setCompanyName(company.getCompanyName());
        }

        List<UserRole> userRoles = userRoleService.findByUserId(user.getUserId());
        List<String> roleCodes = new ArrayList<>();
        userRoles.forEach(userRole -> {
            roleCodes.add(userRole.getRoleCode());
        });
        if (roleCodes.size() > 0) {
            List<Role> roles = roleService.findByRoleCodes(roleCodes);
            userVO.setRoles(roles);
        }
        return userVO;
    }

    @Override
    public void sendValidateCode(String key) {
        Userinfo userinfo = userinfoDao.findByPhoneOrEmail(key);
        if (userinfo == null) {
            throw new EastrocException("用户不存在");
        }

        String code = RandomStringUtils.randomNumeric(4);




    }


    @Override
    public int updatePassword(ChangePasswordVO changePasswordVO) {

        ValidationUtils.validate(changePasswordVO);
        Userinfo currentUser = loginService.getCurrentUser();

        String password = ShiroSaltUtils.generatePassword(changePasswordVO.getOldPassword(), currentUser.getSalt());
        if (!StringUtils.equals(password, currentUser.getPassword())) {
            throw new EastrocException("旧密码输入不对");
        }

        String newPassword = ShiroSaltUtils.generatePassword(changePasswordVO.getNewPassword(), currentUser.getSalt());
        currentUser.setPassword(newPassword);
        return userinfoDao.update(currentUser);
    }
    
    @Override
    public void updateValidateInfo(UserinfoValidateVO userinfoValidateVO) {


    }


    @Override
    public void sendValidateEmail(String email) {}

    @Override
    public void doValidateEmail(String key) {

    }


    @Override
    public void sendResetPasswordEmail(String email) {}
    
    @Override
    public void doResetPassword(ResetPasswordEmailVO resetPasswordEmailVO) {

      
    }
    
    @Override
    public void sendSetPasswordEmail(String email) {}

}
